import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { Group, CreateGroupRequest, UpdateGroupRequest } from '@/types'
import { getGroups, createGroup as createGroupApi, updateGroup as updateGroupApi, deleteGroup as deleteGroupApi } from '@/api'

// 分组状态管理
export const useGroupStore = defineStore('group', () => {
  // 状态 - 初始为空数组，通过API获取数据
  const groups = ref<Group[]>([])
  const currentGroupId = ref<number>(0)
  const isLoading = ref<boolean>(false)

  // 计算属性
  const currentGroup = computed(() => {
    return groups.value.find(group => group.group_id === currentGroupId.value) || null
  })

  const defaultGroup = computed(() => {
    return groups.value.find(group => group.is_default) || null
  })

  // 操作

  /**
   * 获取分组列表
   */
  const fetchGroups = async () => {
    isLoading.value = true
    try {
      // 使用API获取分组列表
      const response = await getGroups()
      groups.value = response
      
      // 如果当前分组ID不存在或无效，设置为默认分组
      if (!currentGroupId.value || !groups.value.some(group => group.group_id === currentGroupId.value)) {
        const defaultGp = defaultGroup.value
        if (defaultGp) {
          currentGroupId.value = defaultGp.group_id
        } else if (groups.value.length > 0) {
          currentGroupId.value = groups.value[0].group_id
        }
      }
      
      return response
    } catch (error) {
      console.error('获取分组列表失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 创建分组
   * @param data 分组创建请求数据
   */
  const createGroup = async (data: CreateGroupRequest) => {
    isLoading.value = true
    try {
      const response = await createGroupApi(data)
      
      // 重新获取分组列表以保持数据同步
      await fetchGroups()
      
      return response
    } catch (error) {
      console.error('创建分组失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 更新分组
   * @param id 分组ID
   * @param data 分组更新请求数据
   */
  const updateGroup = async (id: number, data: UpdateGroupRequest) => {
    isLoading.value = true
    try {
      const response = await updateGroupApi(id, data)
      
      // 重新获取分组列表以保持数据同步
      await fetchGroups()
      
      return response
    } catch (error) {
      console.error('更新分组失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 删除分组
   * @param id 分组ID
   */
  const deleteGroup = async (id: number) => {
    isLoading.value = true
    try {
      await deleteGroupApi(id)
      
      // 重新获取分组列表以保持数据同步
      await fetchGroups()
      
      // 如果删除的是当前分组，切换到默认分组
      if (currentGroupId.value === id) {
        const defaultGp = defaultGroup.value
        if (defaultGp) {
          currentGroupId.value = defaultGp.group_id
        } else if (groups.value.length > 0) {
          currentGroupId.value = groups.value[0].group_id
        } else {
          currentGroupId.value = 0
        }
      }
      
      return { success: true }
    } catch (error) {
      console.error('删除分组失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 设置当前分组
   * @param id 分组ID
   */
  const setCurrentGroup = (id: number) => {
    currentGroupId.value = id
  }

  return {
    groups,
    currentGroupId,
    currentGroup,
    defaultGroup,
    isLoading,
    fetchGroups,
    createGroup,
    updateGroup,
    deleteGroup,
    setCurrentGroup
  }
})
